<?php
declare (strict_types = 1);

namespace app\admin\controller\maichen;

use think\Request;
use think\facade\View;
use think\facade\Request as Rq;
use think\facade\Session;
use think\facade\Db;
use think\exception\ValidateException;
use app\admin\model\Sku;

use app\admin\validate\maichen\Finance as Fi;
use app\admin\validate\maichen\Product as Pv;
use app\common\controller\Base;
use app\admin\model\Finance as Fm;
use app\controller\Wechat as Wx;
use app\admin\model\Product;

class Finance extends Base
{

    public function initialize()
    {

        parent::initialize(); // TODO: Change the autogenerated stub

    }
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $admin= Session::get('admin');
        if (Rq::isPost()) {
            $where = '1 = 1';
            $current_user_id = $admin['id'];
            $group_id = $admin['group_id'];

            switch ($group_id) {
                case 3:
                    $where = ['apply_user_id' => $current_user_id];
                    break;
                default:
                    break;
            }

            $list=Db::name('finance')
                ->where($where)
                ->select();
                return ['code'=>0,'msg'=>lang('get info success'),'data'=>$list];


        }
   
        return view();
    }

    /**
     * 添加记录页面
     * @author Luke
     */
    public function add() {
        $result = [
            'code' => 0,
            'msg' => '添加成功',
        ];
        $data = Rq::only(['amount_money', 'description', 'avatar'], 'post');
        if (Rq::isPost() && count($data) > 0) {
            $admin= Session::get('admin');
            $data['apply_user_id'] = $admin['id'];
            $data['img_url'] = $data['avatar'];
            unset($data['avatar']);
            
            
            try {
                validate(Fi::class)->check($data);
                $fm = new Fm();
                $result = $fm->saveRecard($data);
                if ($result) {
                    $this->success(lang('add success'), url('maichen.Finance/index'));
                }

            } catch (ValidateException $e) {
                $result = [
                    'code' => 1,
                    'msg' => $e->getError(),
                ];

                $this->error( $e->getError());

            }
            
        }

        $view = [
            'title' => '申请',
            'info' => [],
        ];
        View::assign($view);
        return view();
    }

    public function reject() {
        $id = Rq::post('id');
        $admin= Session::get('admin');
        $result = [
            'code' => 0,
            'msg' => '成功驳回请求',
        ];
        $current = Fm::find($id);
        if (is_null($current)) {
            $result = [
                'code' => 1,
                'msg' => 'id 没有对应记录',
            ];
        } else {
            if ($current->status === 0) {
                if ($admin['group_id'] === 2) {
                    $current->reviewer_id = $admin['id'];
                    $current->status = 2;
                    $current->save();
                } else {
                    $result = [
                        'code' => 3,
                        'msg' => '只有财务才有审核权限',
                        ];
                }
                
            } else {
                $result = [
                    'code' => 2,
                    'msg' => '只有未审核才能进行驳回',
                ];
            }
        }

        return json($result);
    }

    public function examine() {
        $id = Rq::post('id');
        $admin= Session::get('admin');
        $result = [
            'code' => 0,
            'msg' => '审核通过',
        ];
        $current = Fm::find($id);
        if (is_null($current)) {
            $result = [
                'code' => 1,
                'msg' => 'id 没有对应记录',
            ];
        } else {
            if ($current->status === 0) {
                if ($admin['group_id'] === 2) {
                    $current->reviewer_id = $admin['id'];
                    $current->status = 1;
                    $current->save();
                } else {
                    $result = [
                        'code' => 3,
                        'msg' => '只有财务才有审核权限',
                        ];
                }
                
            } else {
                $result = [
                    'code' => 2,
                    'msg' => '只有未审核才能进行审核',
                ];
            }
        }

        return json($result);
    }

    public function orderList() {
        $year = 2025;
        $month = 5;
        $first_time = strtotime("first day of $year-$month");
        $end_time = strtotime("first day of next month $year-$month-01");
        
        $wx = new Wx();
        $result = $wx->orderList($first_time, $end_time);
        // $result = $wx->getInfoByOrderId([]);
        halt($result);
    }

    public function productList() {
        if (Rq::isPost()) {
            $key = Rq::post('keys', '', 'trim');
            $page = Rq::post('page', 1);
            $pagesize = Rq::post('limit', 15);
           
            $model = new Product();
            $where0 = [['name', 'like', "%{$key}%"]];
            $where1 = [['material', 'like', "%{$key}%"]];
            $where2 = [['manufacturer', 'like', "%{$key}%"]];
            $list = Product::with('sku')->whereOr([$where0, $where1, $where2])->paginate(['list_rows' => $pagesize, 'page' => $page])->toArray();
            return ['code' => 0, 'msg' => lang('get info success'), 'data' => $list['data'], 'count' => $list['total']];
        }
        return view();
    }

    public function addProduct() {
        
        if (Rq::isPost()) {
            $data = Rq::only(['name', 'material', 'manufacturer', 'avatar', 'shop_no']);
            try {
                validate(Pv::class)->check($data);
                $model = new Product();
                // $data['create_time'] = time();
                $result = $model->save($data);
                if ($result) {
                    $this->success(lang('add success'), url('maichen.Finance/productList'));
                }
            } catch (ValidateException $e) {
                $result = [
                    'code' => 1,
                    'msg' => $e->getError(),
                ];

                $this->error( $e->getError());
            }
            var_dump($data);exit;
        }
        $view = [
            'title' => '产品',
            'info' => [],
        ];

        View::assign($view);
        return view();
    }

    public function productDel() {
        $ids = Rq::post('ids');
        if (!empty($ids)) {
            $model = new Product();

            $model->delProduct($ids);
            $this->success(lang('delete success'));
        } else {
            $this->error(lang('supper man cannot delete'));

        }
    }

    public function addSku()
    {
        $view = [
            'title' => '添加 sku',
            'product_id' =>  Rq::get('id'),
            'info' => '',
        ];
        if (Rq::isPost()) {
            $data = Rq::post()['data'];
            $sku = new Sku();
            foreach ($data as $key => $value) {
                // $data[$key]['create_time'] = time();
                $data[$key]['batch'] = uniqid();
            }
            $sku->saveAll($data);
            $this->success(lang('添加成功'));
        } else {
        }
        View::assign($view);
        return view();
    }
}